<template>
  <div class="flex items-center justify-between mb-[8px]">
    <div class="flex items-center justify-center">
      <SvgIcon icon-class="gonggao1" />
      <span class="ml-[4px] font-bold">飞书日历</span>
    </div>
    <div class="item">
      <!-- {{ calendarTitle }} -->
      <el-date-picker
        v-model="displayRange"
        type="week"
        value-format="YYYY-MM-DD"
        format="YYYY 第 ww 周"
        placeholder="请选择周"
        @change="handleWeekChangeWeek"
        @blur="handleDataBlur"
        ref="weekPicker"
        v-if="isShow && btnActive === 'week'"
      />
      <el-date-picker
        v-model="displayRange"
        type="date"
        value-format="YYYY-MM-DD"
        format="YYYY-MM-DD"
        placeholder="请选择日"
        @blur="handleDataBlur"
        @change="handleWeekChangeDay"
        ref="weekPicker"
        v-if="isShow && btnActive === 'day'"
      />
      <div v-if="!isShow" @click="openPicker" class="calendar_title">
        <span>{{ calendarTitle }}</span>
        <span class="ml-[6px] calendar_title_item"
          ><el-icon><ArrowDown /></el-icon
        ></span>
      </div>
    </div>
    <div class="item flex items-center">
      <el-button-group>
        <el-button @click="calRef.previous()">
          <el-icon class="el-icon--right"><ArrowLeft /></el-icon>
        </el-button>
        <el-button @click="calRef.next()">
          <el-icon class="el-icon--right"><ArrowRight /></el-icon>
        </el-button>
      </el-button-group>
      <el-button type="primary" class="mx-[12px]" @click="handleToday"
        >今天</el-button
      >
      <div>
        <div class="nav-button">
          <span
            :class="btnActive === 'week' ? 'active' : ''"
            @click="handelActive('week')"
            >周</span
          >
          <span
            :class="btnActive === 'day' ? 'active' : ''"
            @click="handelActive('day')"
            >日</span
          >
        </div>
      </div>
    </div>
  </div>
  <vue-cal
    :time-from="1 * 60"
    :time-to="24 * 60"
    :time-step="30"
    :hour-height="80"
    v-model:active-view="activeView"
    v-model:selected-date="selectedDate"
    class="scrollToCurrent"
    :style="{ height: height }"
    ref="calRef"
    :hide-weekends="false"
    :events="events"
    :disable-views="['month', 'year', 'years']"
    today-button
    locale="zh-cn"
    @ready="scrollToCurrentTime"
    :on-event-click="handleEvent"
    @event-dblclick="handleEventDblClick"
    @view-change="handleViewChange"
  >
  </vue-cal>
  <MyPopover ref="popoverRef"></MyPopover>
</template>
<script setup>
import VueCal from "vue-cal";
import SvgIcon from "@/components/SvgIcon/index.vue";
import "vue-cal/dist/vuecal.css";
import "vue-cal/dist/i18n/zh-cn.es.js";
import MyPopover from "./components/MyPopover/index.vue";
import {
  getFeishuCalendarList,
  getFeishuCalendarDetails,
} from "@/api/system/calendar.js";
import {
  getCurrentDate,
  getFormattedDate,
  formatDateRange,
} from "@/utils/time.js";
import { onMounted } from "vue";
const props = defineProps({
  height: { type: String, default: "35vh" },
});
const displayRange = ref();
const btnActive = ref("day");
const calRef = ref();
const selectedDate = ref(getCurrentDate(null));
const events = ref([]);
const calendarTitle = ref(null);
const activeView = ref("day");
const handelActive = (val) => {
  btnActive.value = val == "day" ? "day" : "week";
  activeView.value = val == "day" ? "day" : "week";
};
onMounted(() => {
  handelActive("week");
});
const getList = async (val) => {
  calendarTitle.value = formatDateRange(val.startTime, val.endTime);
  displayRange.value = val.startTime;
  const { data } = await getFeishuCalendarList(val);
  let arr = data.map((item) => {
    const str = {
      start: item.startTime,
      end: item.endTime,
      title: item.summary,
      content: item?.meetingRoom?.[0]?.display_name,
      id: item.id,
      class:
        item.endTime > getCurrentDate(null, "YYYY-MM-DD HH:mm:ss")
          ? "health"
          : "lunch",
    };
    return str;
  });

  events.value = arr.length ? arr : [];
};
// getList({ startTime: getCurrentDate(null), endTime: getCurrentDate(null) });
const handleEvent = (event, e) => {
  popoverRef.value.showPopover({ triggerElement: e.target, id: event.id }); // 点击时显示 Popover
  e.stopPropagation();
};
const popoverRef = ref(null);
const handleEventDblClick = (event, e) => {
  e.stopPropagation();
  e.preventDefault();
};

const handleViewChange = (event) => {
  const { view, startDate, endDate } = event;
  btnActive.value = view == "day" ? "day" : "week";
  if (view == "day") {
    getList({
      startTime: getCurrentDate(startDate),
      endTime: getCurrentDate(startDate),
    });
  } else {
    getList({
      startTime: getCurrentDate(startDate),
      endTime: getCurrentDate(endDate),
    });
  }
  setTimeout(() => {
    scrollToCurrentTime();
  }, 500);
};

const handleToday = () => {
  const today = new Date();
  selectedDate.value = getCurrentDate(null);
  calRef.value.switchView("day", today);
};
const scrollToCurrentTime = () => {
  setTimeout(() => {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const calendar = document.querySelector(".scrollToCurrent .vuecal__bg");
    const homeCalendar = document.querySelector(
      ".homeCalendar .scrollToCurrent .vuecal__bg"
    );
    const timeInMinutes = hours + minutes / 60;
    let sum = timeInMinutes;
    if (sum >= 22) {
      sum += 18;
    } else if (sum >= 17) {
      sum += 14;
    } else if (sum >= 14) {
      sum += 10;
    } else if (sum >= 10) {
      sum += 6;
    } else if (sum >= 7) {
      sum += 4;
    } else if (sum < 3) {
      sum = 0;
    }
    calendar?.scrollTo({ top: sum * 40, behavior: "smooth" });
    homeCalendar?.scrollTo({ top: sum * 40, behavior: "smooth" });
  }, 500);
};

const isShow = ref(false);
const weekPicker = ref();
const openPicker = () => {
  isShow.value = true;
  setTimeout(() => {
    weekPicker.value?.focus();
  });
};
const handleDataBlur = () => {
  isShow.value = false;
};
const handleWeekChangeWeek = (val) => {
  selectedDate.value = val;
  isShow.value = false;
};
const handleWeekChangeDay = (val) => {
  selectedDate.value = val;
  isShow.value = false;
};
const tabChangeActive = inject("tabChangeActive");
watch(
  () => tabChangeActive.value,
  (val) => {
    console.log(1111);
    if (val == "todo") {
      scrollToCurrentTime();
    }
  }
);
</script>
<style lang="scss" scoped>
:deep(.vuecal__menu) {
  display: none;
}
:deep(.vuecal__title-bar) {
  background-color: #eeeeee;
  .vuecal__title {
    font-size: 16px;
  }
}
:deep(.vuecal__event.health) {
  background-color: #e0e9ff;
  border-radius: 8px;
  font-size: 12px;
  text-align: left;
  color: #3487ff;
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    height: 100%;
    width: 5px;
    background-color: #3487ff;
  }
}
:deep(.vuecal__event.lunch) {
  background: repeating-linear-gradient(
    135deg,
    transparent,
    transparent 5px,
    /* 减小间距 */ #e0e9ff 5px,
    #e0e9ff 15px /* 减小间距 */
  ); /* IE 10+ */
  color: #3487ff;
  text-align: left;
  font-size: 12px;
  align-items: center;
  border: 1px dashed #3487ff;
  border-radius: 8px;
  opacity: 0.6;
}
:deep(.vuecal__event-time) {
  margin: 0 10px;
}
:deep(.vuecal__event-title) {
  margin-left: 10px;
  font-weight: 700;
}
:deep(.vuecal__today-btn) {
  width: 150px;
}
.nav-button {
  overflow: hidden;
  display: flex;
  border: 1px solid #e6e7e9;
  line-height: 28px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  color: #333;
  width: 90px;
  margin-top: 2px;
  background-color: #fafafa;

  span {
    flex: 1;
    align-items: center;
    display: flex;
    justify-content: center;
    vertical-align: middle;
    border-radius: 4px;
    margin: 2px;
    &.active {
      background: #3188ff;
      color: #fff;
    }
  }
}
:deep(.vuecal__now-line) {
  color: red !important;
}
:deep(.vuecal__title-bar) {
  display: none;
}
:deep(.vuecal__event-content) {
  margin-left: 10px;
}
:deep(.vuecal__event-title) {
  margin-left: 10px;
}
.calendar_title {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 8px;
  &:hover {
    background: #e0e0e0;
  }
  .calendar_title_item {
    vertical-align: text-top;
  }
}
</style>
